package com.hw.hcit;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.app.StatusBarManager;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import android.app.ActivityManager;
import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.JCtrlCallback;
import com.hw.hcit.conf.JTestItem;

import android.os.PowerManager.WakeLock;
import android.os.storage.StorageEventListener;
import android.os.storage.StorageManager;
public class MainActivity extends Activity implements JCtrlCallback {

	// JTestItem tis[];
	// List<JTestItem> tis = new ArrayList<JTestItem>();
	// List<JTestItem> pros = new ArrayList<JTestItem>();
	private WifiManager mWifiManager;
	private BluetoothAdapter mBluetoothAdapter;
	private StatusBarManager mStatusBarManager;
	private String TAG = "MainActivity";
	private boolean ageTested = true;
	private PowerManager mPowerManager;
	private WakeLock mWakeLock;
	private Toast mToast;
	private String path = "persist/mmi_result.txt";
	
	Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {

        	Config.ageingTested = isAgeingTested();
        	Log.d("XX","ageingTested--->" +Config.ageingTested);
        	

        }
    };
	private boolean creatFile(String path){
		
//		private char[] initChars = 
		File mFile = new File(path);
		if(!mFile.exists()){
			try {
				mFile.createNewFile();	
			} catch (Exception e) {
				// TODO: handle exception
				Log.d(TAG, "file create error="+e);
			}
			StringBuilder stringBuilder = new StringBuilder();
			String mreString = "";
			for(int i=0;i<64;i++){
				stringBuilder.append("U");
			}
			mreString = stringBuilder.toString();
			Log.d(TAG, "string.lenght-->"+mreString.length());
			try
			{	
				FileOutputStream outStream = new FileOutputStream(mFile);
				OutputStreamWriter writer = new OutputStreamWriter(outStream,"gb2312");
				writer.write(mreString);
				writer.flush();
				writer.close();
				outStream.close();
			}
			catch (Exception e)
			{
				Log.d(TAG, "file write error="+e);
			} 
		}
		
		if(mFile.exists()){
			return true;
		}
		return false;
	}
	
	 private  String readfile(String filePath) {
	        StringBuilder txtContent = new StringBuilder();
	        byte[] b = new byte[1];
	        InputStream in = null;
	        try {
	            in = new FileInputStream(filePath);
	            while (in.read(b) != -1) {
	                String s  = new String(b);
	                txtContent.append(s);
	            }
	            in.close();
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            if (in != null) {
	                try {
	                    in.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        return txtContent.toString();
	    }
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (Config.STEP <= Config.UI_PROJECTS) {
			super.onBackPressed();
		} else if (Config.STEP >= Config.UI_TEST_BASE) {
			if (Config.CURR_PROJECT.isAuto()) {
				goUI(Config.UI_PROJECTS);
			} else {
				goUI(Config.UI_PROJECT);
			}
		} else if (Config.STEP <= Config.UI_PROJECT) {
			goUI(Config.UI_PROJECTS);
		} else if (Config.STEP == Config.UI_RESULT) {
			goUI(Config.UI_PROJECTS);
		}
	}


    private boolean isAgeingTested() {
    	boolean mmitested = false;
    	 String mmi= readfile(path);

    	 Log.d("XX","mmi-length-->" +mmi.length());
    	 Log.d("XX","mmi--->" +mmi);
         if(mmi !=null && !"".equals(mmi) && mmi.length()== 64){
         	char[] c = mmi.toCharArray();
         	Log.d("XX","c.length-->" +c.length);
         	Log.d("XX","c[62]-->" +c[62]);
         	mmitested = c[62]=='P' ;
         	Log.d("XX","mmi-1-->" +mmitested);
         	return mmitested;
         }
         Log.d("XX","mmi-2-->" +mmitested);
        return mmitested;
    }

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	/*15-10-28 gaoshenpan add judge if runing monkeyTest begin*/
	public static boolean isMonkeyRunning() {
		return ActivityManager.isUserAMonkey();
	}
	/*15-10-28 gaoshenpan add judge if runing monkeyTest end*/
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		// getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_SCRIM);

		setContentView(R.layout.activity_main);
		Log.d(TAG,"---m-------->onCreate");
		/*15-10-28 gaoshenpan if runing monkeyTest this finish begin*/
		if(isMonkeyRunning()){
			Log.d(TAG,"---m-is------->onCreate");
			this.finish();
		}
		/*15-10-28 gaoshenpan if runing monkeyTest this finish end*/
		// test();
		Config.cb = this;

		loadTestModel();
		loadProjects();

		mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		mStatusBarManager = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE);

		Config.STEP = Config.UI_PROJECTS;
		this.getFragmentManager().beginTransaction()
				.replace(R.id.frame_layout, Config.PROJECTS.getUI()).commit();
		mPowerManager = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
		mWakeLock = this.mPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
	}
    
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		/*15-11-12 gaoshenpan fix judge isMonkeyRuning when onResume begin*/
		Log.d(TAG,"---m-------->onResume()");
		if(isMonkeyRunning()){
			Log.d(TAG,"---m---is----->onResume()");
			this.finish();
		}
		boolean fileExist = creatFile(path);
		Log.d(TAG, "fileExist--->"+fileExist);
		/*15-11-12 gaoshenpan fix judge isMonkeyRuning when onResume end*/
		/*15-09-08 gaoshenpan fix nv not read caused StringIndexOutOfBoundsException begin*/
		/*15-09-29 gaoshenpan fiv nv not ready after Runintime begin*/
		mToast = new Toast(this);
		/*15-09-29 gaoshenpan fiv nv not ready after Runintime end*/
		mHandler.sendEmptyMessage(0);
		/*15-09-08 gaoshenpan fix nv not read caused StringIndexOutOfBoundsException end*/
		mWifiManager.setWifiEnabled(true);
		mBluetoothAdapter.enable();
		Settings.Global.putInt(getContentResolver(), "mmi_test_running", 1);
		disableStatusBar(true);
		mWakeLock.acquire();
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		/*15-10-22 fix remove handler when onpause begin*/
		Log.d(TAG, "mainActivity--->onPause()");
		/*15-09-29 gaoshenpan fiv nv not ready after Runintime begin*/
		if (mToast != null) {
            mToast.cancel();
            Log.d(TAG, "mNv == null--->mToast.cancel()");
        }
		/*15-09-29 gaoshenpan fiv nv not ready after Runintime end*/
		mHandler.removeMessages(0);
		/*15-10-22 fix remove handler when onpause end*/
		mWifiManager.setWifiEnabled(false);
		mBluetoothAdapter.disable();
		Settings.Global.putInt(getContentResolver(), "mmi_test_running", 0);
		disableStatusBar(false);
		mWakeLock.release();
		
	}

	private void disableStatusBar(boolean disable) {
		if (mStatusBarManager == null)
			return;
		if (disable) {
			int state = StatusBarManager.DISABLE_NONE;
			state |= StatusBarManager.DISABLE_EXPAND;
			mStatusBarManager.disable(state);
		} else {
			mStatusBarManager.disable(StatusBarManager.DISABLE_NONE);
		}
	}

	private void loadTestModel() {
		try {
			Resources res = getResources();
			XmlResourceParser xml = res.getXml(R.xml.testmodel);
			int xmlEventType;
			while ((xmlEventType = xml.next()) != XmlResourceParser.END_DOCUMENT) {
				if (xml.getName() != null
						&& xmlEventType == XmlResourceParser.START_TAG) {
					if (xml.getName().equals("TestItem")) {
						String name = xml.getAttributeValue(null, "name");
						String classname = xml.getAttributeValue(null,
								"classname");
						Config.RegsterItem(name, classname);
					}
				}
			}
			xml.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void loadProjects() {
		try {
			Config.PROJECTS = null;// new JProjects();
			Resources res = getResources();
			XmlResourceParser xml = res.getXml(R.xml.project);
			int xmlEventType;
			JProject pro = null;
			JCase item = null;
			// walk through senders.xml file.
			while ((xmlEventType = xml.next()) != XmlResourceParser.END_DOCUMENT) {
				// if (xmlEventType == XmlResourceParser.START_TAG ||
				// xmlEventType == XmlResourceParser.END_TAG)
				if (xml.getName() != null) {
					if (xml.getName().equals("Projects")) {
						if (xmlEventType == XmlResourceParser.START_TAG) {
							Config.PROJECTS = new JProjects();

							int d = xml.getAttributeResourceValue(null, "name",
									-1);
							if (d == -1) {
								Config.PROJECTS.setName(xml.getAttributeValue(
										null, "name"));
							} else {
								Config.PROJECTS.setName(res.getString(d));
							}
							Config.PROJECTS.setUI(Config.GetItem("projects",
									this));
						} else if (xmlEventType == XmlResourceParser.END_TAG) {
							break;
						}
					} else if (Config.PROJECTS != null
							&& xml.getName().equals("Project")) {
						if (xmlEventType == XmlResourceParser.START_TAG) {
							pro = new JProject();

							int d = xml.getAttributeResourceValue(null, "name",
									-1);
							if (d == -1) {
								pro.setName(xml.getAttributeValue(null, "name"));
							} else {
								pro.setName(res.getString(d));
							}
							String s = xml.getAttributeValue(null, "auto");
							if (s != null && s.equals("true")) {
								pro.setAuto(true);
							}

							pro.setType(xml.getAttributeValue(null, "type"));
							pro.setUI(Config.GetItem("project", this));

							s = xml.getAttributeValue(null, "endFeature");
							if (s == null || s.length() == 0) {
								pro.setEndUI(Config.GetItem("defautEnd", this));
							} else {
								pro.setEndUI(Config.GetItem(s, this));
							}
						} else if (pro != null
								&& xmlEventType == XmlResourceParser.END_TAG) {
							Config.PROJECTS.add(pro);
							pro = null;
						}
					} else if (pro != null && xml.getName().equals("Item")) {
						if (xmlEventType == XmlResourceParser.START_TAG) {
							String s = xml.getAttributeValue(null, "feature");
							boolean b = Config.getExsit(s);
							if (b) {
								item = new JCase();

								int d = xml.getAttributeResourceValue(null,
										"name", -1);
								if (d == -1) {
									item.setName(xml.getAttributeValue(null,
											"name"));
								} else {
									item.setName(res.getString(d));
								}

								item.setFeature(xml.getAttributeValue(null,
										"feature"));
								String auto = xml.getAttributeValue(null,
										"autoNext");
								if (auto != null && auto.equals("true")) {
									item.setAutoNext(true);
								}
								item.setUI(Config.GetItem(item.getFeature(),
										this));
							}
						} else if (item != null
								&& xmlEventType == XmlResourceParser.END_TAG) {
							pro.add(item);
							item = null;
						}
					}
				}
			}
			xml.close();
		} catch (Exception e) {
			e.printStackTrace();
			Config.PROJECTS = null;
		}
	}

	// @Override
	// public void goBackTest() {
	// // TODO Auto-generated method stub
	// if(Config.STEP >= Config.UI_TEST_BASE)
	// {
	// Config.STEP ++;
	// if(Config.STEP - Config.UI_TEST_BASE >= Config.CURR_PROJECT.getSize())
	// {
	// goUI(Config.UI_RESULT);
	// }
	// else
	// {
	// goUI(Config.STEP);
	// Config.CURR_CASE.getUI().startTest();
	// }
	// }
	// }
	//

	@Override
	public void action(boolean b) {
		action(b, 1, false);
	}

	@Override
	public void action(boolean b, int step, boolean onlyMove) {
		// TODO Auto-generated method stub
		// this.getFragmentManager().beginTransaction().replace(R.id.frame_layout,
		// Config.projects.getUI()).commit();
		if (Config.STEP == Config.UI_PROJECTS) {
			JTestItem item = Config.PROJECTS.getUI();
			int v = Integer.parseInt(item.getResultInfo());
			Config.CURR_PROJECT = Config.PROJECTS.getValue(v);
			Config.STEP = Config.UI_PROJECT;
			// this.getFragmentManager().beginTransaction().replace(R.id.frame_layout,
			// Config.curr_pro.getUI()).commit();
			if (Config.CURR_PROJECT.isAuto()) {
				Config.STEP = Config.UI_TEST_BASE;
				goUI(Config.UI_TEST_BASE);
				// Config.CURR_CASE.getUI().startTest();
			} else {
				goUI(Config.UI_PROJECT);
			}
		} else if (Config.STEP == Config.UI_PROJECT) {
			if (!Config.CURR_PROJECT.isAuto()) // not auto
			{
				int index = Integer.parseInt(Config.CURR_PROJECT.getUI()
						.getResultInfo());
				// Config.curr_case = Config.curr_pro.getValue(index);
				Config.STEP = Config.UI_TEST_BASE + index;
				// this.getFragmentManager().beginTransaction().replace(R.id.frame_layout,
				// Config.curr_case.getUI()).commit();
				goUI(Config.UI_TEST_BASE + index);
				// Config.CURR_CASE.getUI().startTest();
			}
		} else if (Config.STEP >= Config.UI_TEST_BASE) {
			if (!onlyMove) {
				Config.CURR_CASE.setResult(b);
			}
			if (step != Config.UI_HOLD) {
				int index = Config.STEP - Config.UI_TEST_BASE;
				if (!Config.CURR_PROJECT.isAuto()) // not auto
				{
					goUI(Config.UI_PROJECT);
				} else {
					goNextCaseUI(step);
				}
			}
		}

	}

	private void goNextCaseUI(int step) {
		if (Config.STEP >= Config.UI_TEST_BASE) {
			Config.STEP += step;
			if (Config.STEP - Config.UI_TEST_BASE >= Config.CURR_PROJECT
					.getSize()) {
				goUI(Config.UI_RESULT);
			} else if (Config.STEP - Config.UI_TEST_BASE < 0) {
				Config.STEP -= step;
			} else {
				goUI(Config.STEP);
				// Config.CURR_CASE.getUI().startTest();
			}
		}
	}

	private void goUI(int p) {
		if (p == Config.UI_PROJECTS) {
			Config.STEP = p;
			this.getFragmentManager().beginTransaction()
					.replace(R.id.frame_layout, Config.PROJECTS.getUI())
					.commit();
			Config.PROJECTS.getUI().refresh();
		} else if (p == Config.UI_PROJECT) {
			Config.STEP = p;
			this.getFragmentManager().beginTransaction()
					.replace(R.id.frame_layout, Config.CURR_PROJECT.getUI())
					.commit();
			Config.CURR_PROJECT.getUI().refresh();
		} else if (p >= Config.UI_TEST_BASE) {
			Config.STEP = p;
			Config.CURR_CASE = Config.CURR_PROJECT.getValue(Config.STEP
					- Config.UI_TEST_BASE);
			Config.CURR_CASE.resetResult();
			this.getFragmentManager().beginTransaction()
					.replace(R.id.frame_layout, Config.CURR_CASE.getUI())
					.commit();
			Config.CURR_CASE.getUI().refresh();
		} else if (p == Config.UI_RESULT) {
			Config.STEP = p;
			this.getFragmentManager().beginTransaction()
					.replace(R.id.frame_layout, Config.CURR_PROJECT.getEndUI())
					.commit();
			Config.CURR_PROJECT.getEndUI().refresh();
		}
	}

	 @Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int keyCode = event.getKeyCode();
		if (Config.CURR_PROJECT != null
				&& Config.CURR_CASE != null
				&& Config.CURR_CASE.getFeature().equals("KeypadTest")
				&& Config.STEP >= Config.UI_TEST_BASE) {
			Log.d(TAG, "CURR_CASE is Keypad test");
			switch (keyCode) {
			case KeyEvent.KEYCODE_VOLUME_DOWN:
			case KeyEvent.KEYCODE_VOLUME_UP:
			case KeyEvent.KEYCODE_POWER:
				if (event.getAction() == KeyEvent.ACTION_UP) {
					return Config.CURR_CASE.getUI().dispatchKeyEvent(event);
				}
				return true;
			}
		}
		if (Config.CURR_PROJECT != null
				&& Config.CURR_CASE != null
				&& Config.CURR_CASE.getFeature().equals(
						"HeadsetWireControlTest")
				&& Config.STEP >= Config.UI_TEST_BASE) {
			Log.d(TAG, "CURR_CASE is Headset wire control test");
			switch (keyCode) {
			case KeyEvent.KEYCODE_HEADSETHOOK:
				if (event.getAction() == KeyEvent.ACTION_UP) {
					return Config.CURR_CASE.getUI().dispatchKeyEvent(event);
				}
			}
		}
		if (Config.CURR_PROJECT != null && Config.CURR_CASE != null
				&& (Config.CURR_PROJECT.isAuto() || Config.CURR_CASE.getFeature().equals("LCDTestItem"))
				&& Config.STEP >= Config.UI_TEST_BASE) {
			switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				if (event.isLongPress()) {
					finish();
					return true;
				} else {
					return false;
				}
			case KeyEvent.KEYCODE_VOLUME_DOWN:
				if (Config.CURR_CASE != null
						&& event.getAction() == KeyEvent.ACTION_DOWN) {
					return Config.CURR_CASE.getUI().dispatchKeyEvent(event);
				}
				return true;
			case KeyEvent.KEYCODE_VOLUME_UP:
				if (Config.CURR_CASE != null
						&& event.getAction() == KeyEvent.ACTION_DOWN) {
					return Config.CURR_CASE.getUI().dispatchKeyEvent(event);
				}
				return true;
			case KeyEvent.KEYCODE_POWER:
				if (Config.CURR_CASE != null) {
					/*
					 * Config.CURR_CASE.getUI().testFinish(false,
					 * Config.UI_HOLD, false);
					 */
					Config.CURR_CASE.getUI().dispatchKeyEvent(event);
				}
				return true;
			}
		}
		return super.dispatchKeyEvent(event);

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (Config.CURR_CASE != null) {
			Config.CURR_CASE.getUI().onTouchEvent(event);
		}
		return super.onTouchEvent(event);
	}

}
